<!-- /components/MonthPickerPopup.vue -->
<template>
	<uni-popup ref="popupRef" type="bottom" background-color="rgba(0,0,0,0.4)" :z-index="20000">
		<view class="picker-container" :style="{ paddingBottom: safeAreaBottom }">
			<view class="picker-header">
				<text class="btn cancel" @click="handleCancel">取消</text>
				<text class="title">{{ titleText }}</text>
				<text class="btn confirm" @click="handleConfirm">确定</text>
			</view>

			<picker-view
				class="picker-view"
				:value="pickerValue"
				@change="handleChange"
				indicator-class="indicator"
				indicator-style="height: 50px;"
			>
				<picker-view-column>
					<view class="column-item" v-for="year in years" :key="year">{{ year }}年</view>
				</picker-view-column>
				<picker-view-column>
					<view class="column-item" v-for="month in dynamicMonths" :key="month">{{ month }}月</view>
				</picker-view-column>
				<picker-view-column v-if="isDateMode || isDatetimeMode">
					<view class="column-item" v-for="day in dynamicDays" :key="day">{{ day }}日</view>
				</picker-view-column>
				<!-- 新增：时/分/秒列（仅在 datetime 模式下显示） -->
				<picker-view-column v-if="isDatetimeMode">
					<view class="column-item" v-for="hour in dynamicHours" :key="hour">{{ ('0' + hour).slice(-2) }}时</view>
				</picker-view-column>
				<picker-view-column v-if="isDatetimeMode">
					<view class="column-item" v-for="minute in dynamicMinutes" :key="minute">{{ ('0' + minute).slice(-2) }}分</view>
				</picker-view-column>
				<picker-view-column v-if="isDatetimeMode">
					<view class="column-item" v-for="second in dynamicSeconds" :key="second">{{ ('0' + second).slice(-2) }}秒</view>
				</picker-view-column>
			</picker-view>
		</view>
	</uni-popup>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import UniPopup from '/uni_modules/uni-popup/components/uni-popup/uni-popup.vue';

const props = defineProps({
  type: { type: String, default: 'month' } // 'month' | 'date' | 'datetime'
});
const isDateMode = computed(() => props.type === 'date');
const isDatetimeMode = computed(() => props.type === 'datetime');

const emit = defineEmits(['confirm', 'cancel']);
const popupRef = ref(null);

// 获取安全区底部（适配 iPhone）
const safeAreaBottom = ref('0rpx');
onMounted(() => {
	uni.getSystemInfo({
		success: (res) => {
			if (res.safeAreaInsets) {
				safeAreaBottom.value = res.safeAreaInsets.bottom + 'px';
			}
		}
	});
});

// 当前时间
const now = new Date();
const currentYear = now.getFullYear();
const currentMonth = now.getMonth() + 1; // 1-12
const currentDay = now.getDate();
const currentHour = now.getHours();
const currentMinute = now.getMinutes();
const currentSecond = now.getSeconds();

// 年份范围：过去5年 + 今年（升序）
const years = Array.from({ length: 6 }, (_, i) => currentYear - i).reverse();

// 选择值与可选数据
const valueMonth = ref([0, 0]); // [yearIndex, monthIndex]
const valueDate = ref([0, 0, 0]); // [yearIndex, monthIndex, dayIndex]
const valueDatetime = ref([0, 0, 0, 0, 0, 0]); // [yearIndex, monthIndex, dayIndex, hourIndex, minuteIndex, secondIndex]
const dynamicMonths = ref([...Array(12).keys()].map(i => i + 1)); // 默认 1-12
const dynamicDays = ref([...Array(31).keys()].map(i => i + 1)); // 默认 1-31
const dynamicHours = ref([...Array(24).keys()].map(i => i));
const dynamicMinutes = ref([...Array(60).keys()].map(i => i));
const dynamicSeconds = ref([...Array(60).keys()].map(i => i));

// 标题与绑定值
const titleText = computed(() => (isDatetimeMode.value ? '选择日期时间' : (isDateMode.value ? '选择日期' : '选择年月')));
const pickerValue = computed(() => (isDatetimeMode.value ? valueDatetime.value : (isDateMode.value ? valueDate.value : valueMonth.value)));

// 初始化选中值（默认当前年月/日/时分秒）
const initValue = () => {
  const yearIndex = years.indexOf(currentYear);
  const monthIndex = currentMonth - 1;
  if (isDatetimeMode.value) {
    valueDatetime.value = [yearIndex, monthIndex, currentDay - 1, currentHour, currentMinute, currentSecond];
    updateMonthsByYear(yearIndex);
    updateDaysByYearMonth(yearIndex, monthIndex);
  } else if (isDateMode.value) {
    valueDate.value = [yearIndex, monthIndex, currentDay - 1];
    updateMonthsByYear(yearIndex);
    updateDaysByYearMonth(yearIndex, monthIndex);
  } else {
    valueMonth.value = [yearIndex, monthIndex];
    updateMonthsByYear(yearIndex);
  }
};

// 根据选中的年份更新可选月份
const updateMonthsByYear = (yearIndex) => {
  const selectedYear = years[yearIndex];
  if (selectedYear === currentYear) {
    // 今年：只能选 1 ~ currentMonth
    dynamicMonths.value = Array.from({ length: currentMonth }, (_, i) => i + 1);
    // 修正月份索引
    if (isDatetimeMode.value) {
      if (valueDatetime.value[1] >= dynamicMonths.value.length) {
        valueDatetime.value[1] = dynamicMonths.value.length - 1;
      }
    } else if (isDateMode.value) {
      if (valueDate.value[1] >= dynamicMonths.value.length) {
        valueDate.value[1] = dynamicMonths.value.length - 1;
      }
    } else {
      if (valueMonth.value[1] >= dynamicMonths.value.length) {
        valueMonth.value[1] = dynamicMonths.value.length - 1;
      }
    }
  } else {
    // 往年：1-12 全开
    dynamicMonths.value = Array.from({ length: 12 }, (_, i) => i + 1);
  }
};

// 根据选中的年/月更新天数
const updateDaysByYearMonth = (yearIndex, monthIndex) => {
  const year = years[yearIndex];
  const month = dynamicMonths.value[monthIndex];
  const daysInMonth = new Date(year, month, 0).getDate();
  if (year === currentYear && month === currentMonth) {
    dynamicDays.value = Array.from({ length: Math.min(daysInMonth, currentDay) }, (_, i) => i + 1);
  } else {
    dynamicDays.value = Array.from({ length: daysInMonth }, (_, i) => i + 1);
  }
  // 修正 dayIndex 越界
  if (isDatetimeMode.value) {
    if (valueDatetime.value[2] >= dynamicDays.value.length) {
      valueDatetime.value[2] = dynamicDays.value.length - 1;
    }
  } else if (isDateMode.value) {
    if (valueDate.value[2] >= dynamicDays.value.length) {
      valueDate.value[2] = dynamicDays.value.length - 1;
    }
  }
};

// 打开弹窗
const open = () => {
  initValue();
  popupRef.value.open();
};

// 滚动选择事件
const handleChange = (e) => {
  const val = e.detail.value;
  if (isDatetimeMode.value) {
    valueDatetime.value = val;
    updateMonthsByYear(val[0]);
    updateDaysByYearMonth(val[0], val[1]);
  } else if (isDateMode.value) {
    valueDate.value = val;
    updateMonthsByYear(val[0]);
    updateDaysByYearMonth(val[0], val[1]);
  } else {
    valueMonth.value = val;
    updateMonthsByYear(val[0]);
  }
};

// 确认
const pad2 = (n) => ('0' + n).slice(-2);
const handleConfirm = () => {
  const yearIndex = isDatetimeMode.value ? valueDatetime.value[0] : (isDateMode.value ? valueDate.value[0] : valueMonth.value[0]);
  const monthIndex = isDatetimeMode.value ? valueDatetime.value[1] : (isDateMode.value ? valueDate.value[1] : valueMonth.value[1]);
  const selectedYear = years[yearIndex];
  const selectedMonth = dynamicMonths.value[monthIndex];
  if (isDatetimeMode.value) {
    const dayIndex = valueDatetime.value[2];
    const selectedDay = dynamicDays.value[dayIndex];
    const h = pad2(dynamicHours.value[valueDatetime.value[3]]);
    const m = pad2(dynamicMinutes.value[valueDatetime.value[4]]);
    const s = pad2(dynamicSeconds.value[valueDatetime.value[5]]);
    emit('confirm', `${selectedYear}年${selectedMonth}月${selectedDay}日 ${h}:${m}:${s}`);
  } else if (isDateMode.value) {
    const dayIndex = valueDate.value[2];
    const selectedDay = dynamicDays.value[dayIndex];
    emit('confirm', `${selectedYear}年${selectedMonth}月${selectedDay}日`);
  } else {
    emit('confirm', `${selectedYear}年${selectedMonth}月`);
  }
  popupRef.value.close();
};

// 取消
const handleCancel = () => {
  emit('cancel');
  popupRef.value.close();
};

defineExpose({ open });
</script>

<style scoped lang="scss">
.picker-container {
	width: 100%;
	max-height: 70vh;
	background: #fff;
	border-top-left-radius: 24rpx;
	border-top-right-radius: 24rpx;
	overflow: hidden;
	box-shadow: 0 -10rpx 30rpx rgba(0, 0, 0, 0.1);
}

.picker-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 24rpx 36rpx;
	background: #fff;
	font-size: 32rpx;
	color: #333;
	border-bottom: 1px solid #eee;
}

.btn {
	font-size: 30rpx;
	color: #007aff;
}

.title {
	font-weight: 500;
	color: #000;
}

.picker-view {
	height: 360rpx;
	width: 100%;
}

.column-item {
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 34rpx;
	color: #333;
	height: 50px;
	line-height: 50px;
}

.indicator {
	background: rgba(0, 122, 255, 0.1);
	border-top: 1px solid #e0e0e0;
	border-bottom: 1px solid #e0e0e0;
}
</style>